package com.ruoyi.demo.task;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.demo.domain.AuctionGoods;
import com.ruoyi.demo.domain.AuctionSession;
import com.ruoyi.demo.domain.AuctionOrder;
import com.ruoyi.demo.service.IAuctionGoodsService;
import com.ruoyi.demo.service.IAuctionOrderService;
import com.ruoyi.demo.service.IAuctionRecordService;
import com.ruoyi.demo.service.IAuctionSessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 拍卖和商品状态修改定时任务
 * @author metaee
 */
@Component
public class AuctionDealTask {
    
    private static final Logger log = LoggerFactory.getLogger(AuctionDealTask.class);

    @Autowired
    private IAuctionGoodsService auctionGoodsService;

    @Autowired
    private IAuctionRecordService auctionRecordService;

    @Autowired
    private IAuctionOrderService auctionOrderService;

    @Autowired
    private IAuctionSessionService auctionSessionService;

    /**
     * 拍卖成交定时任务
     * 每分钟执行一次，检查已结束的拍卖商品并处理成交
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void dealEndedAuctions() {
        log.info("开始执行拍卖成交定时任务 - {}", DateUtils.getTime());
        
        // 创建查询条件
        AuctionGoods queryParam = new AuctionGoods();
        queryParam.setStatus("1"); // 竞拍中的商品
        List<AuctionGoods> goodsList = auctionGoodsService.selectAuctionGoodsList(queryParam);
        
        log.info("待处理的竞拍中商品数量: {}", goodsList.size());

        Date now = DateUtils.getNowDate();

        for (AuctionGoods goods : goodsList) {
            // 检查是否已结束
            if (goods.getEndTime() != null && goods.getEndTime().before(now)) {
                try {
                    log.info("开始处理商品ID: {}, 商品名称: {}", goods.getGoodsId(), goods.getGoodsName());
                    
                    // 检查是否已经有订单
                    AuctionOrder queryOrder = new AuctionOrder();
                    queryOrder.setGoodsId(goods.getGoodsId());
                    List<AuctionOrder> existOrders = auctionOrderService.selectAuctionOrderList(queryOrder);
                    if (existOrders != null && !existOrders.isEmpty()) {
                        log.info("商品ID: {} 已存在订单，跳过处理", goods.getGoodsId());
                        continue; // 如果已经有订单，跳过处理
                    }

                    // 调用成交接口
                    auctionOrderService.createDealOrder(goods.getGoodsId());
                    log.info("商品ID: {} 创建订单成功", goods.getGoodsId());

                    // 更新商品状态为已结束
                    AuctionGoods updateGoods = new AuctionGoods();
                    updateGoods.setGoodsId(goods.getGoodsId());
                    updateGoods.setStatus("2"); // 已结束
                    auctionGoodsService.updateAuctionGoods(updateGoods);
                    log.info("商品ID: {} 状态更新为已结束", goods.getGoodsId());
                } catch (Exception e) {
                    // 记录异常，但不影响其他商品的处理
                    log.error("处理商品{}成交失败：{}", goods.getGoodsId(), e.getMessage(), e);
                }
            }
        }
        
        log.info("拍卖成交定时任务执行完成 - {}", DateUtils.getTime());
    }

    /**
     * 每分钟执行一次，更新专场和商品状态
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void updateAuctionStatus() {
        log.info("开始执行状态更新定时任务 - {}", DateUtils.getTime());
        
        Date now = DateUtils.getNowDate();

        // 更新专场状态
        updateSessionStatus(now);

        // 更新商品状态
        updateGoodsStatus(now);
        
        log.info("状态更新定时任务执行完成 - {}", DateUtils.getTime());
    }

    /**
     * 更新专场状态
     */
    private void updateSessionStatus(Date now) {
        log.info("开始更新专场状态");
        
        // 1. 更新待开始->竞拍中的专场
        AuctionSession queryStarting = new AuctionSession();
        queryStarting.setStatus("0"); // 待开始
        List<AuctionSession> startingSessions = auctionSessionService.selectAuctionSessionList(queryStarting);
        log.info("待开始的专场数量: {}", startingSessions.size());

        for (AuctionSession session : startingSessions) {
            if (session.getStartTime() != null && session.getStartTime().before(now)) {
                log.info("专场ID: {} 开始竞拍", session.getSessionId());
                AuctionSession updateSession = new AuctionSession();
                updateSession.setSessionId(session.getSessionId());
                updateSession.setStatus("1"); // 竞拍中
                auctionSessionService.updateAuctionSession(updateSession);
            }
        }

        // 2. 更新竞拍中->已结束的专场
        AuctionSession queryEnding = new AuctionSession();
        queryEnding.setStatus("1"); // 竞拍中
        List<AuctionSession> endingSessions = auctionSessionService.selectAuctionSessionList(queryEnding);
        log.info("竞拍中的专场数量: {}", endingSessions.size());

        for (AuctionSession session : endingSessions) {
            if (session.getEndTime() != null && session.getEndTime().before(now)) {
                log.info("专场ID: {} 结束竞拍", session.getSessionId());
                AuctionSession updateSession = new AuctionSession();
                updateSession.setSessionId(session.getSessionId());
                updateSession.setStatus("2"); // 已结束
                auctionSessionService.updateAuctionSession(updateSession);
            }
        }
    }

    /**
     * 更新商品状态
     */
    private void updateGoodsStatus(Date now) {
        log.info("开始更新商品状态");
        
        // 1. 更新待开始->竞拍中的商品
        AuctionGoods queryStarting = new AuctionGoods();
        queryStarting.setStatus("0"); // 待开始
        List<AuctionGoods> startingGoods = auctionGoodsService.selectAuctionGoodsList(queryStarting);
        log.info("待开始的商品数量: {}", startingGoods.size());

        for (AuctionGoods goods : startingGoods) {
            if (goods.getStartTime() != null && goods.getStartTime().before(now)) {
                log.info("商品ID: {} 开始竞拍", goods.getGoodsId());
                AuctionGoods updateGoods = new AuctionGoods();
                updateGoods.setGoodsId(goods.getGoodsId());
                updateGoods.setStatus("1"); // 竞拍中
                auctionGoodsService.updateAuctionGoods(updateGoods);
            }
        }

        // 2. 更新竞拍中->已结束的商品
        AuctionGoods queryEnding = new AuctionGoods();
        queryEnding.setStatus("1"); // 竞拍中
        List<AuctionGoods> endingGoods = auctionGoodsService.selectAuctionGoodsList(queryEnding);
        log.info("竞拍中的商品数量: {}", endingGoods.size());

        for (AuctionGoods goods : endingGoods) {
            if (goods.getEndTime() != null && goods.getEndTime().before(now)) {
                log.info("商品ID: {} 结束竞拍", goods.getGoodsId());
                AuctionGoods updateGoods = new AuctionGoods();
                updateGoods.setGoodsId(goods.getGoodsId());
                updateGoods.setStatus("2"); // 已结束
                auctionGoodsService.updateAuctionGoods(updateGoods);
            }
        }
    }
}
